package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.zzyl.base.ResponseResult;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.ResourceDto;
import com.zzyl.entity.Resource;
import com.zzyl.entity.RoleResource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.service.ResourceService;
import com.zzyl.utils.NoProcessing;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.ResourceVo;
import com.zzyl.vo.TreeItemVo;
import com.zzyl.vo.TreeVo;
import net.sf.jsqlparser.expression.LongValue;
import org.assertj.core.api.SoftAssertionsProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description ResuorceServiceImpl
 * @Author apeng
 * @Date 2024-10-23
 */
@Service
public class ResourceServiceImpl implements ResourceService {

    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private RoleResourceMapper roleResourceMapper;

    @Override
    public List<ResourceVo> findResourceList(ResourceDto resourceDto) {
        List<ResourceVo> resourceList = resourceMapper.findResourceList(resourceDto);
        return resourceList;
    }

    //资源树形
    @Override
    public TreeVo resourceTreeVo(ResourceDto resourceDto) {
        //构建查询条件
        ResourceDto dto = ResourceDto.builder()
                .parentResourceNo(NoProcessing.processString(SuperConstant.ROOT_PARENT_ID))
                .resourceType(SuperConstant.MENU)
                .dataState(SuperConstant.DATA_STATE_0)
                .build();
        //获得所有的节点列表
        List<ResourceVo> resourceList = resourceMapper.findResourceList(dto);
        if (ObjectUtil.isAllEmpty(resourceList)){
            throw new RuntimeException("没有菜单");
        }
        //将节点列表转成树形
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setNameKey("label");
        List<Tree<String>> treeList = TreeUtil.build(resourceList, SuperConstant.ROOT_PARENT_ID, treeNodeConfig,
                (resourceVo, treeNode) -> {
                    treeNode.setParentId(resourceVo.getParentResourceNo());
                    treeNode.setId(resourceVo.getResourceNo());
                    treeNode.setName(resourceVo.getResourceName());
                });
        //将List<Tree<String>>转成List<Tree<ResourceVo>>
        List<TreeItemVo> treeItemVoList = BeanUtil.copyToList(treeList, TreeItemVo.class);
        //构建树形
        TreeItemVo itemVo = TreeItemVo.builder()
                .id(SuperConstant.ROOT_PARENT_ID)
                .label("智慧养老院")
                .children(treeItemVoList)
                .build();
        //构建item
        List<TreeItemVo> itemVos = new ArrayList<>();
        itemVos.add(itemVo);
        return TreeVo.builder().items(itemVos).build();
    }

    @Override
    public ResponseResult createResource(ResourceDto resourceDto) {
        Resource resource = BeanUtil.toBean(resourceDto, Resource.class);
        //查找父资源的状态，并同步父资源和子资源的状态
        Resource parentResourceNo  = resourceMapper.selectByResourceNo(resourceDto.getParentResourceNo());
        resource.setDataState(parentResourceNo.getDataState());
        //生成子资源的编号
        String resourceNo = createResourceNo(resourceDto);
        resource.setResourceNo(resourceNo);
        //添加到数据库中
        resourceMapper.insertSelective(resource);
        return ResponseResult.success(true);
    }

    //生成子资源的编号
    private String createResourceNo(ResourceDto resourceDto) {
        //判断是菜单并且父资源编号是否大于四，大于四就抛出异常
        if (resourceDto.getResourceType().equals("m")
                && NoProcessing.processString(resourceDto.getParentResourceNo()).length()/3 > 4){
            throw  new BaseException(BasicEnum.RESOURCE_DEPTH_UPPER_LIMIT);
        }

        //如果不超过，就判断夫资源下是否有节点
        ResourceDto dto = ResourceDto.builder().parentResourceNo(resourceDto.getParentResourceNo()).build();
        List<ResourceVo> resourceList = resourceMapper.findResourceList(dto);
        if (ObjectUtil.isNotEmpty(resourceList)){
            //如果有节点，就取出最大的节点，并加一,true就是添加兄弟节点
            //将所有节点的resourceno取出来，封装成集合
            List<String> list = resourceList.stream().map(ResourceVo::getResourceNo).collect(Collectors.toList());
            Long resourceNoMax = list.stream().map(i -> Long.valueOf(i)).max(Comparator.comparing(i -> i)).get();
            return NoProcessing.createNo(resourceNoMax.toString(), true);
        }else {
            //如果没有节点，就创建节点，false就是添加的子节点
            return NoProcessing.createNo(resourceDto.getParentResourceNo(), false);
        }
    }

    //资源修改
    @Override
    public ResponseResult<Boolean> updateResource(ResourceDto resourceDto) {
        if (resourceDto.getResourceType().equals("m")
                && NoProcessing.processString(resourceDto.getParentResourceNo()).length()/3 > 4){
            throw  new BaseException(BasicEnum.RESOURCE_DEPTH_UPPER_LIMIT);
        }
        Resource resource = BeanUtil.toBean(resourceDto, Resource.class);
        resourceMapper.updateByPrimaryKeySelective(resource);
        return ResponseResult.success(true);
    }

    //启用禁用
    @Override
    public ResponseResult<Boolean> startOrStop(ResourceDto resourceDto) {
        //判断父资源是否为禁用状态，如果为禁用状态，不允许启用
        Resource ParentResource = resourceMapper.selectByResourceNo(resourceDto.getParentResourceNo());
        if(ParentResource.getDataState().equals("1")){
            throw new BaseException(BasicEnum.PARENT_DEPT_DISABLE);
        }
        resourceMapper.updateByResourcNo(resourceDto.getResourceNo(),resourceDto.getDataState());
        resourceMapper.updateByParentResourceNo(NoProcessing.processString(resourceDto.getResourceNo()),resourceDto.getDataState());
        return ResponseResult.success(true);
    }

    //删除资源
    @Override
    public void updateByResourcNo(String resourceNo) {
        //如果在禁用状态下，存在子菜单，不允许删除
        List<Resource> list = resourceMapper.findByResourceNo(resourceNo);
        if (list != null && list.size() > 0) {
            throw new RuntimeException("存在子菜单,不允许删除");
        }
        //已被分配，则不允许删除
       Integer count = roleResourceMapper.findByResourcesNo(resourceNo);
        if (count > 0){
            throw new RuntimeException("已被分配,不允许删除");
        }
        resourceMapper.deleteByResourceNo(resourceNo);
    }
}
